package pt.isel.pdm.yamba;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class StatusActivity extends Activity implements OnClickListener, OnSharedPreferenceChangeListener {
	private Button submit;
	private EditText text;
	private TextView charsRemaining;
	private SharedPreferences prefs;
	private boolean buttonEnabled;
	private Intent statusUploadService;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.status);
        submit = (Button) findViewById(R.id.buttonUpdate);
        submit.setOnClickListener(this);
        text = (EditText) findViewById(R.id.editText);
        charsRemaining = (TextView) findViewById(R.id.remainingChars);
        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.registerOnSharedPreferenceChangeListener(this);
    	charsRemaining.setText(prefs.getString("msgsize", "140") + " " + getString(R.string.textRemaining));
    	text.setFilters(new InputFilter[]{new InputFilter.LengthFilter(Integer.parseInt(prefs.getString("msgsize", "140")))});
        text.addTextChangedListener(new TextWatcher(){
			@Override
			public void afterTextChanged(Editable arg0) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
		    	charsRemaining.setText(Integer.parseInt(prefs.getString("msgsize", null)) - text.length() + " " + getString(R.string.textRemaining));
		    	text.setFilters(new InputFilter[]{new InputFilter.LengthFilter(Integer.parseInt(prefs.getString("msgsize", null)))});
			}
        });
        
        if (prefs.getString("username", null) == null || prefs.getString("password", null) == null){
        	startActivity(new Intent(this, PreferencesActivity.class)); 
        }
        Global.username = prefs.getString("username", null);
        Global.password = prefs.getString("password", null);
        Global.apiuri = prefs.getString("apiuri", null);
        statusUploadService = new Intent(this, StatusUpload.class);
        Global.timelinePullService = new Intent(this, TimelinePull.class);
        Global.msgstoshow = Integer.parseInt(prefs.getString("maxmsg", "10"));
        Global.msgskept = Integer.parseInt(prefs.getString("msgskept", "10"));
    	Global.autotlpull = prefs.getBoolean("autotlpull", true);
    	Global.pullInterval = Integer.parseInt(prefs.getString("pullinterval", "30"));
        buttonEnabled = true;
    }

	public void onSharedPreferenceChanged(SharedPreferences sp, String s) {
    	int maxChars = Integer.parseInt(prefs.getString("msgsize", null));
    	if(text.length() > maxChars)
    		text.setText(text.getText().subSequence(0, maxChars));
    	charsRemaining.setText(maxChars - text.length() + " " + getString(R.string.textRemaining));
    	try{
			if(s.equals("username") && !Global.username.equals(prefs.getString("username", null))){
				Global.username = prefs.getString("username", null);
				Global.resetTwitter();
				return;
			}
			if(s.equals("password") && !Global.password.equals(prefs.getString("password", null))){
				Global.password = prefs.getString("password", null);
				Global.resetTwitter();
				return;
			}
			if(s.equals("apiuri") && !Global.apiuri.equals(prefs.getString("apiuri", null))){
				Global.apiuri = prefs.getString("apiuri", null);
				Global.resetTwitter();
				return;
			}
			if(s.equals("autotlpull")){
				Global.autotlpull = prefs.getBoolean("autotlpull", true);
				synchronized(Global.timelinePullWait){
					Global.timelinePullWait.notify();
				}
			}
    	}catch(Exception e){}
        Global.msgstoshow = Integer.parseInt(prefs.getString("maxmsg", "10"));
		Global.msgskept = Integer.parseInt(prefs.getString("msgskept", "10"));
		Global.pullInterval = Integer.parseInt(prefs.getString("pullinterval", "30"));
	}
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.status, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
	    	case R.id.user:
	        	startActivity(new Intent(this, UserActivity.class));
	    		return true;
	    	case R.id.status:
	    		return true;
	    	case R.id.preferences:
	        	startActivity(new Intent(this, PreferencesActivity.class));
	        	return true;
	    	case R.id.timeline:
	        	startActivity(new Intent(this, TimelineActivity.class));
	        	return true;
	    	case R.id.refresh:
	    		startService(Global.timelinePullService);
	    		return true;
	    	default:
	    		return super.onOptionsItemSelected(item);
    	}
	}
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        submit.setEnabled(buttonEnabled);
        if(buttonEnabled)
        	submit.setText(R.string.buttonUpdateFace);
        else
	    	submit.setText(R.string.buttonBusyFace);
    }
	@Override
    public void onClick(View v) {
		buttonEnabled = false;
		submit.setEnabled(false);
    	submit.setText(R.string.buttonBusyFace);
    	statusUploadService.putExtra(StatusUpload.DATA, text.getText().toString());
        startService(statusUploadService);
		buttonEnabled = true;
		submit.setEnabled(true);
    	submit.setText(R.string.buttonUpdateFace);
	}
}
